import React, { useState, useRef, useEffect } from 'react'
import { Languages, Check } from 'lucide-react'
import { useTranslation, Language } from '@/utils/i18n'

const LanguageSwitcher: React.FC = () => {
  const { locale, setLocale, t } = useTranslation()
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  const languages: { value: Language; label: string; flag: string }[] = [
    { value: 'zh-CN', label: t('language.zhCN'), flag: '🇨🇳' },
    { value: 'en-US', label: t('language.enUS'), flag: '🇺🇸' },
  ]

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="p-2.5 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-all duration-200 relative group"
        title={t('language.zhCN')}
      >
        <Languages size={18} />
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-48 bg-white rounded-xl shadow-lg border border-gray-200 py-2 z-50 animate-slide-up">
          {languages.map((lang) => (
            <button
              key={lang.value}
              onClick={() => {
                setLocale(lang.value)
                setIsOpen(false)
              }}
              className={`
                w-full flex items-center justify-between px-4 py-2.5 text-sm transition-colors
                ${locale === lang.value
                  ? 'bg-blue-50 text-blue-600'
                  : 'text-gray-700 hover:bg-gray-50'
                }
              `}
            >
              <div className="flex items-center gap-2">
                <span className="text-lg">{lang.flag}</span>
                <span>{lang.label}</span>
              </div>
              {locale === lang.value && (
                <Check size={16} className="text-blue-600" />
              )}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}

export default LanguageSwitcher

